var peta;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var oldDirections = [];
var currentDirections = null;
var curr_marker = 0;
var base_url = '';
var option_list = '';
var option_route = '';
var id_route_detail = 0;

function initialize(){
    var jogja = new google.maps.LatLng(-7.78283, 110.36698);
    var petaoption = {
        zoom: 14,
        center: jogja,
        mapTypeId: google.maps.MapTypeId.TERRAIN
        };
    peta = new google.maps.Map(document.getElementById("petaku"),petaoption);
	LoadMarkers();
	
    directionsDisplay = new google.maps.DirectionsRenderer({
        'map': peta,
        'preserveViewport': true,
        'draggable': true
    });


    google.maps.event.addListener(peta,'click',function(event){
        addMark(event.latLng);
    });
	
    google.maps.event.addListener(directionsDisplay, 'directions_changed',
      function() {
        if (currentDirections) {
          oldDirections.push(currentDirections);
        }
        currentDirections = directionsDisplay.getDirections();
      });
	  //calcRoute('','');
}

function saveLatLong(name, lat, lng) {
	var theurl = base_url +"gmap/gmap/saveLatLong";
	var thedata = "lat="+lat+"&lng="+lng+"&name="+name;
	$.ajax({
	    url: theurl,
	    data: thedata,
		type: 'POST',
		async: false,
	    cache: false,
	    success: function(msg){
	    	curr_marker = msg;
	    }
	});
}

function addMark(lokasi) {
	var name = prompt('What is the name of this Mark?');
	if (name) {
		saveLatLong(name, lokasi.lat(), lokasi.lng());
		addMarker(curr_marker, name, lokasi.lat(), lokasi.lng())
	}
}

function GetRoutes() {
	if (option_route.length > 0)
		return;
	
	var theurl = base_url + "gmap/gmap/loadRoutes";
	$.ajax({
		type: "GET",
		url: theurl,
		dataType: "json",
		async: false,
		success: function (data) {
			option_route = data;
		}
	});
}

function CreateRoute(source_id, target_id) {
	start_coord	= source_id.split('|');
	var start 	= new google.maps.LatLng(start_coord[1], start_coord[2]);
	end_coord 	= target_id.split('|');
	var end 	= new google.maps.LatLng(end_coord[1], end_coord[2]);
	
//	alert($('#route_dir').val());
	SaveRouteDetail($('#route_dir').val(), start_coord[0], end_coord[0]);
	calcRoute(start,end);

//	alert(source_id + ' ' + target_id);
}

function SaveRouteDetail(id_route, id_from, id_to) {
	var theurl = base_url +"gmap/gmap/saveRouteDetail";
	var thedata = "id_route="+id_route+"&id_from="+id_from+"&id_to="+id_to;
	$.ajax({
	    url: theurl,
	    data: thedata,
		type: 'POST',
		async: false,
	    cache: false,
	    success: function(msg){
	    	id_route_detail = msg;
	    }
	});
}

function createShelterOptions(current_id, lat, lng) {
	var current_data = current_id + '|' + lat + '|' + lng;
	var strSelect = '<select id="target_dir_"' + current_id + ' onchange="CreateRoute(\'' + current_data + '\',this.value)">';
	
//	alert(option_list);
	strSelect += '<option value="0" selected="selected">-- Pilih Target --</option>';
	$(option_list).find('marker').each(function() {
		var marker = $(this);
		if (current_id != marker.attr('id')) {
			var thevalue = marker.attr('id') + '|' + marker.attr('lat') + '|' + marker.attr('lng');
			strSelect += '<option value="' + thevalue + '">' + marker.attr('name') + '</option>';
		}
	});
	strSelect += '</select>'; 
	return strSelect;
}

function createRouteOptions() {
	var strSelect = '<select id="route_dir">';
	
//	alert(option_list);
	strSelect += '<option value="0" selected="selected">-- Pilih Rute --</option>';
	$.each(option_route, function() {
		var route = this;
		strSelect += '<option value="' + route.id_route + '">' + route.route_name + '</option>';
	});
	strSelect += '</select>'; 
	return strSelect;
}

function createSaveButton() {
	return strSave = '<input type="button" onclick="SaveVertex()" value="Save Vertex" />';
}

function SaveVertex() {
	var poly = currentDirections.routes;
	var arrPoly = new Array();
	var steps = poly[0].legs[0].steps;
	
	var i = 0;
	$.each(steps, function() {
		var step = this;
		var arrTemp = new Array();
		arrTemp[0] = step.start_location.lat();
		arrTemp[1] = step.start_location.lng();
		arrTemp[2] = step.end_location.lat();
		arrTemp[3] = step.end_location.lng();
		arrPoly[i] = arrTemp;
		i++;
	});
	
	alert(JSON.stringify(arrPoly));
	id_route_detail = 4;
	var theurl = base_url +"gmap/gmap/saveRouteDetailVertex";
	var thedata = "id_route_detail=" + id_route_detail + "&latlng=" + JSON.stringify(arrPoly);
	$.ajax({
	    url: theurl,
	    data: thedata,
		type: 'POST',
		async: false,
	    cache: false,
	    success: function(msg){
	    	//print_path();
	    }
	});
}

function infoWindow(current_id, name, lat, lng) {
	GetRoutes();
	
	//get option list
	var html = '<b>'+ name + '</b>';
	html += '<br /> Lat: ' +lat + ' Lng: ' +  lng + '<br />';
	html += '<br />Rute: ';
	html += createRouteOptions();
	html += '<br />Connect to: ';
	html += createShelterOptions(current_id, lat, lng);
	html += '<br />' + createSaveButton();
	
	return html;
}

function addMarker(id, name, lat, lng){
	var point = new google.maps.LatLng(lat, lng);
    var tanda = new google.maps.Marker({
        position: point,
        map: peta,
		draggable: true
    });
	
    var html = infoWindow(id, name, lat, lng);
    var infowindow = new google.maps.InfoWindow({
        content: html
    });
    google.maps.event.addListener(tanda, 'click', function() {
      infowindow.open(peta,tanda);
    });
    google.maps.event.addListener(tanda, 'dragend', function(event) {
        SaveMarker(id,event.latLng);
      });
}

function updateMarkerPosition(latLng) {  
  document.getElementById('info').innerHTML = [  
    latLng.lat(),  
    latLng.lng()  
  ].join(', ');  
}  

function calcRoute(start, end) {
	if (start == '')
		start = 'Malioboro, Yogyakarta';
	if (end == '')
		end = 'Jalan Parangtritis, Yogyakarta';
	
	var request = {
	    origin:start,
	    destination:end,
	    travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
	directionsService.route(request, function(response, status) {
	  if (status == google.maps.DirectionsStatus.OK) {
	    directionsDisplay.setDirections(response);
	  }
	});
}

function SaveMarker(id, latlng) {
	var thedata = 'id=' + id + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();
	var theurl = base_url + "gmap/gmap/SaveMarker";

	$.ajax({
		type: "POST",
		url: theurl,
		data: thedata,
		success: function (data) {
			$(data).find('marker').each(function() {
			  	var marker = $(this);
				addMarker(marker.attr('name'), marker.attr("lat"), marker.attr("lng"))
			});	
		}
	});
}

function LoadMarkers() {
	var theurl = base_url + "gmap/gmap/loadMarkers";
	$.ajax({
		type: "GET",
		url: theurl,
		dataType: "xml",
		success: function (data) {
			$(data).find('marker').each(function() {
				option_list = data;
			  	var marker = $(this);
				addMarker(marker.attr('id'), marker.attr('name'), marker.attr("lat"), marker.attr("lng"))
			});	
		}
	});
}